const app = getApp();

Page({

  data: {
    socketStatus: 'closed',
    messages: [],
    inputMessage: '',
    room_id:'',
    closeType:0,
    my_user_id:0,
  },

  onLoad(options) {
    const room_id = options.room_id;
    this.setData({
        room_id: room_id,
        my_user_id:app.globalData.userInfo.id
    });
  },
  onUnload(){
      console.log('page out')
      this.closeSocket()
      this.setData({
        closeType:1 
    });
  },
  onInputChange(e) {
    this.setData({
      inputMessage: e.detail.value
    });
  },
    onShow: function() {
        var that = this;
        if (that.data.socketStatus === 'closed') {
            console.log('had closed');
            that.openSocket();
        }
    },
    connectSocket(){
        wx.connectSocket({
            url: "ws://" + "localhost" + ":8080/api/ws?roomid="+this.data.room_id,
            header: {
              'Content-type': 'application/json',
              'Authorization': `Bearer ${app.globalData.token}`
            },
        })
    },
  openSocket() {
   //打开时的动作
    wx.onSocketOpen(() => {
      console.log('WebSocket 已连接')
      this.data.socketStatus = 'connected';
      this.setData({
        messages: []
      });
      //this.sendMessage();
    })
    //断开时的动作
    wx.onSocketClose(() => {
      console.log('WebSocket 已断开')
      this.data.socketStatus = 'closed'

      if (this.data.closeType == 0) {
         this.connectSocket();
      }
    })
    //报错时的动作
    wx.onSocketError(error => {
      console.error('socket error:', error)
    })
    // 监听服务器推送的消息
    wx.onSocketMessage(message => {
      //把JSONStr转为JSON
      message = message.data.replace(" ", "");
      if (typeof message != 'object') {
        message = message.replace(/\ufeff/g, ""); //重点
        var jj = JSON.parse(message);
        message = jj;
      }
      console.log("【websocket监听到消息】内容如下：");

      this.setData({
        messages: [...this.data.messages, ...message.contents.reverse()]
      });

      console.log(message.contents);
    })
    // 打开信道
    this.connectSocket();

  },
//关闭信道
  closeSocket() {
    if (this.data.socketStatus === 'connected') {
      wx.closeSocket({
        success: () => {
          this.data.socketStatus = 'closed'
        }
      })
    }
  },
 //发送消息函数
  sendMessage() {
    if (!this.data.inputMessage.trim()) {
        return;
      }
    if (this.data.socketStatus === 'connected') {
    //自定义的发给后台识别的参数 ，我这里发送的是name
      wx.sendSocketMessage({
        data: this.data.inputMessage
      })

      this.setData({
        inputMessage: ''
      });
    }
  },
}); 